package com.ayz.gateway.server.grpc.connection;

import com.ayz.gateway.server.grpc.GrpcServerConstants;
import io.grpc.*;

/**
 * @ClassName GrpcConnectionIntercpetor
 * @Description TODO: Grpc连接的拦截器 在每次服务端服务被调用前都会被拦截器拦截
 * 主要任务是设置当前请求的上下文参数项
 * @Author 快乐的星球
 * @Date 2023/5/19 20:31
 * @Version 1.0
 **/
public class GrpcConnectionInterceptor implements ServerInterceptor {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall,
                                                                 Metadata metadata,
                                                                 ServerCallHandler<ReqT, RespT> serverCallHandler) {
        Context ctx= Context.current().withValue(GrpcServerConstants.CONTEXT_KEY_CONN_ID,
                serverCall.getAttributes().get(GrpcServerConstants.ATTR_TRANS_KEY_CONN_ID))
                .withValue(GrpcServerConstants.CONTEXT_KEY_CONN_LOCAL_PORT,
                        serverCall.getAttributes().get(GrpcServerConstants.ATTR_TRANS_KEY_LOCAL_PORT))
                .withValue(GrpcServerConstants.CONTEXT_KEY_CONN_REMOTE_IP,
                        serverCall.getAttributes().get(GrpcServerConstants.ATTR_TRANS_KEY_REMOTE_IP))
                .withValue(GrpcServerConstants.CONTEXT_KEY_CONN_REMOTE_PORT,
                        serverCall.getAttributes().get(GrpcServerConstants.ATTR_TRANS_KEY_REMOTE_PORT));

        return Contexts.interceptCall(ctx,serverCall,metadata,serverCallHandler);
    }
}
